/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['services/config'], function (config) {

    var pager = function () {
        this.currentPage = ko.observable(1);
        this.totalItemCount = ko.observable(0);

        this.pageSize = config.api.defaultListPageSize;

        this.nbOfPages = ko.computed(function () {
            return Math.ceil(this.totalItemCount() / this.pageSize);
        }.bind(this));

        this.pages = ko.computed(function () {
            return calculatePages(this.currentPage(), this.nbOfPages());
        }.bind(this));
    };

    pager.prototype.activate = function (settings) {

        this.pageSize = settings.pageSize || config.api.defaultListPageSize;
        this.currentPage(settings.pageNbr);

        this.totalItemCount(settings.totalItemCount);
    };


    return pager;


    function calculatePages(currentPage, nbOfPages) {

        var pages = [
            {nb: 1, label: '&laquo;', active: false}
        ];

        var lower = Math.floor((currentPage - 1) / 4) * 4 + 1;
        var higher = Math.ceil(currentPage / 4) * 4;

        if (lower > 1) {
            pages.push({nb: lower - 1, label: '..', active: false});
        }

        for (var i = lower; i <= higher && i <= nbOfPages; i++) {
            pages.push({nb: i, label: i.toString(), active: i === +currentPage});
        }

        if (higher < nbOfPages) {
            pages.push({nb: higher + 1, label: '..', active: false});
        }

        pages.push({nb: nbOfPages, label: '&raquo;', active: false});

        return pages;
    }

});